package com.qf.commons.web.exception;


import com.qf.commons.standar.exception.IExceptionHandler;
import com.qf.data.base.r.Codes;
import com.qf.data.base.r.R;
import com.qf.data.base.r.Rs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Autowired(required = false)
    private List<IExceptionHandler> exceptionHandlers;

    /**
     * 统一异常处理 - 处理所有的业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e) {

        //日志记录
        if (exceptionHandlers != null) {
            //循环执行异常处理器
            for (IExceptionHandler exceptionHandler : exceptionHandlers) {
                //判断是否为匹配的异常
                if (exceptionHandler.isSupport(e)) {
                    //当前是需要处理的异常
                    R result = exceptionHandler.exceptionHandler(e);
                    if (result != null) return result;
                }
            }
        }
        log.error("[global exception] 全局异常触发！", e);
        return Rs.createFail(Codes.FAIL);
    }
}
